package com.autoglm.android.core.services

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 语音识别状态
 */
sealed class SpeechRecognitionState {
    object Ready : SpeechRecognitionState()
    object Listening : SpeechRecognitionState()
    object Processing : SpeechRecognitionState()
    data class Results(val text: String, val confidence: Float) : SpeechRecognitionState()
    data class Error(val errorCode: Int, val errorMessage: String) : SpeechRecognitionState()
}

/**
 * 语音识别服务，将用户语音转换为文本
 */
class SpeechRecognitionService(private val context: Context) {
    
    private var speechRecognizer: SpeechRecognizer? = null
    private val _state = MutableStateFlow<SpeechRecognitionState>(SpeechRecognitionState.Ready)
    val state: StateFlow<SpeechRecognitionState> = _state.asStateFlow()
    
    init {
        initializeSpeechRecognizer()
    }
    
    /**
     * 初始化语音识别器
     */
    private fun initializeSpeechRecognizer() {
        if (SpeechRecognizer.isRecognitionAvailable(context)) {
            speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context)
            speechRecognizer?.setRecognitionListener(createRecognitionListener())
        } else {
            _state.value = SpeechRecognitionState.Error(
                -1, 
                "语音识别功能不可用，请检查设备支持和权限设置"
            )
        }
    }
    
    /**
     * 创建识别监听器
     */
    private fun createRecognitionListener(): RecognitionListener {
        return object : RecognitionListener {
            override fun onReadyForSpeech(params: Bundle?) {
                _state.value = SpeechRecognitionState.Listening
            }
            
            override fun onBeginningOfSpeech() {
                // 已经在onReadyForSpeech中处理
            }
            
            override fun onRmsChanged(rmsdB: Float) {
                // 可以用于更新UI上的音量指示器
            }
            
            override fun onBufferReceived(buffer: ByteArray?) {
                // 接收到语音数据缓冲
            }
            
            override fun onEndOfSpeech() {
                _state.value = SpeechRecognitionState.Processing
            }
            
            override fun onError(error: Int) {
                val errorMessage = when (error) {
                    SpeechRecognizer.ERROR_AUDIO -> "音频录制错误"
                    SpeechRecognizer.ERROR_CLIENT -> "客户端错误"
                    SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "权限不足"
                    SpeechRecognizer.ERROR_NETWORK -> "网络错误"
                    SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "网络超时"
                    SpeechRecognizer.ERROR_NO_MATCH -> "未能匹配语音"
                    SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "识别器忙"
                    SpeechRecognizer.ERROR_SERVER -> "服务器错误"
                    SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "语音超时"
                    else -> "未知错误"
                }
                
                _state.value = SpeechRecognitionState.Error(error, errorMessage)
            }
            
            override fun onResults(results: Bundle?) {
                val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
                val confidenceScores = results?.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES)
                
                if (!matches.isNullOrEmpty()) {
                    val recognizedText = matches[0]
                    val confidence = confidenceScores?.let { if (it.isNotEmpty()) it[0] else 0f } ?: 0f
                    
                    _state.value = SpeechRecognitionState.Results(recognizedText, confidence)
                } else {
                    _state.value = SpeechRecognitionState.Error(
                        SpeechRecognizer.ERROR_NO_MATCH,
                        "未能识别语音内容"
                    )
                }
            }
            
            override fun onPartialResults(partialResults: Bundle?) {
                // 部分识别结果，可用于实时显示
                val matches = partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
                
                if (!matches.isNullOrEmpty()) {
                    val recognizedText = matches[0]
                    _state.value = SpeechRecognitionState.Results(recognizedText, 0f)
                }
            }
            
            override fun onEvent(eventType: Int, params: Bundle?) {
                // 其他事件
            }
        }
    }
    
    /**
     * 开始监听语音输入
     * @param languageModel 语言模型，默认为中文
     */
    fun startListening(languageModel: String = "zh-CN") {
        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
            putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
            putExtra(RecognizerIntent.EXTRA_LANGUAGE, languageModel)
            putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1)
            putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
        }
        
        try {
            _state.value = SpeechRecognitionState.Ready
            speechRecognizer?.startListening(intent)
        } catch (e: Exception) {
            _state.value = SpeechRecognitionState.Error(-1, "启动语音识别失败: ${e.message}")
        }
    }
    
    /**
     * 停止监听
     */
    fun stopListening() {
        speechRecognizer?.stopListening()
    }
    
    /**
     * 取消识别
     */
    fun cancel() {
        speechRecognizer?.cancel()
        _state.value = SpeechRecognitionState.Ready
    }
    
    /**
     * 释放资源
     */
    fun destroy() {
        speechRecognizer?.destroy()
        speechRecognizer = null
    }
} 